package cn.kennylee.codehub.springboot.microtrace.feign;

import cn.kennylee.codehub.springboot.microtrace.TraceProperties;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

/**
 * <p>Feign链路追踪拦截器</p>
 * <p>Created on 2025/5/10.</p>
 *
 * @author kennylee
 * @since 0.0.1
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class TraceIdFeignInterceptor implements RequestInterceptor {

    private final TraceProperties traceProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {

        if (requestTemplate.headers().containsKey(traceProperties.getTraceHeaderName())) {
            // 如果请求头中已经存在 Trace ID，则直接返回
            log.info("请求头中已经存在 Trace ID: {}", requestTemplate.headers().get(traceProperties.getTraceHeaderName()));
            return;
        }

        String traceId = MDC.get(traceProperties.getMdcTraceIdName());
        if (StringUtils.hasLength(traceId)) {
            log.trace("设置 Trace ID: {}", traceId);
            requestTemplate.header(traceProperties.getTraceHeaderName(), traceId);
        } else {
            log.debug("找不到 Trace ID，可能是因为没有设置 MDC");
        }
    }
}
